package servlet;

import jakarta.servlet.*;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@WebServlet(
        name = "UploadImageServlet",
        urlPatterns = {"/UploadImageServlet"},
        loadOnStartup = 1
)
@MultipartConfig(
        fileSizeThreshold = 2 * 1024 * 1024, // 2MB
        maxFileSize = 20 * 1024 * 1024,      // 20MB
        maxRequestSize = 40 * 1024 * 1024     // 40MB
)
public class UploadImageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置图片保存目录
        String uploadDir = "C:\\javaweb\\mybatis\\ww1\\src\\main\\webapp\\img";
        System.out.println(uploadDir);
        File dir = new File(uploadDir);


        // 获取上传的文件部分
        Part part = request.getPart("image");
        String fileName = extractFileName(part);
        Path filePath = Paths.get(dir.getAbsolutePath(), fileName);

        // 保存图片
        try (InputStream input = part.getInputStream();
             BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(filePath))) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = input.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
        }

        // 打印图片名字
        System.out.println("图片名字: " + fileName);
        /*
        * 调用mybatis接口，将图片名字存入数据库
        * */
    }

    // 提取上传文件的原始文件名
    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            s = s.trim();
            if (s.startsWith("filename")) {
                return s.substring(s.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return "unknown";
    }
}